from cryptography.fernet import Fernet
from configparser import ConfigParser
import os, sys
from datetime import date

# 加密函数
def encrypt_message(message, key):
    f = Fernet(key)
    encrypted_message = f.encrypt(message.encode())
    return encrypted_message

# 解密函数
def decrypt_message(encrypted_message, key):
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message).decode()
    return decrypted_message


if __name__ == '__main__':
    try:
        assert os.path.exists('config.ini')
    except Exception as e:
        print("缺少config.ini文件：", e)
        sys.exit()

    config = ConfigParser()
    config.read('config.ini')

    key = b'jVJZA3zs-9zGPwLzHyVJVhybqiS0CKvaTHl4aB3omn8='  # 可用方法Fernet.generate_key()生成一个，但代码中要固定，不能变化
    days = 30  # 程序可以使用的天数

    # 读取加密的running_counter
    try:
        encrypt_counter = config.get('licensing', 'running_counter').encode('utf-8')
        encrypt_date = config.get('licensing', 'start_day').encode('utf-8')
    except Exception as e:
        print(e)
        sys.exit()
    running_counter = int(decrypt_message(encrypt_counter, key),2)  # 运行次数
    start_day = int(decrypt_message(encrypt_date, key), 2)

    # 判断程序是否超过限定次数
    if running_counter <= 0:
        print("Error (counter limit): ", running_counter)  # ("程序使用已经超过了限定次数，请咨询程序开发者！")
        sys.exit()
    
    # 判断当前如期是否在合法使用日期之内
    curr_day = date.today().toordinal()
    if (curr_day < start_day) or (curr_day > start_day + days):
        print("Error (time limit)!")
        sys.exit()

    running_counter -= 1
    config.set('licensing', 'running_counter', encrypt_message(bin(running_counter), key).decode('utf-8'))
    # 更新配置文件
    with open("config.ini", 'w') as configfile:
        config.write(configfile)

    # === 继续执行主程序 ===
    print("程序运行成功！")
